import os
#import flaskr
from flaskr import app
from flaskr import flaskr
import unittest
import tempfile

execfile(app.root_path + '/constants.py')


## test constants ##

HELLO_MSG         = '<Hello>'
HELLO_ESCAPED_MSG = '&lt;Hello&gt;'
HTML_ALLOWED_MSG  = '<strong>HTML</strong> allowed'


class FlaskrTestCase(unittest.TestCase):

  ## helpers ##

  def setUp(self):
    self.db_fd , flaskr.app.config[DB_KEY] = tempfile.mkstemp()
    flaskr.app.config[TESTING_KEY]         = True
    self.app                               = flaskr.app.test_client()

    with flaskr.app.app_context():
      flaskr.init_db()


  def tearDown(self):
    os.close(self.db_fd)
    os.unlink(flaskr.app.config[DB_KEY])


  def login(self, username, password):
    params = dict(username = username , password = password)

    return self.app.post(LOGIN_ROUTE , data = params , follow_redirects = True)


  def logout(self):
    return self.app.get(LOGOUT_ROUTE , follow_redirects = True)


## tests ##

  def test_empty_db(self):
    resp = self.app.get(ROOT_ROUTE)
    assert NO_ENTRIES_MSG in resp.data


  def test_login_logout(self):
    assert LOGIN_ERROR_MSG in self.login('ADMIN_LOGIN' ,  ADMIN_PASS ).data
    assert PASS_ERROR_MSG  in self.login( ADMIN_LOGIN  , 'ADMIN_PASS').data
    assert LOGIN_MSG       in self.login( ADMIN_LOGIN  ,  ADMIN_PASS ).data
    assert LOGOUT_MSG      in self.logout().data


  def test_messages(self):
    params = dict(title = HELLO_MSG , text = HTML_ALLOWED_MSG)
    resp   = self.app.post(ADD_ROUTE , data = params , follow_redirects = True)
    assert UNAUTHORIZED_MSG in resp.data
    self.login(ADMIN_LOGIN , ADMIN_PASS)

    resp   = self.app.post(ADD_ROUTE , data = params , follow_redirects = True)
    assert NO_ENTRIES_MSG    not in resp.data
    assert HELLO_ESCAPED_MSG     in resp.data
    assert HTML_ALLOWED_MSG      in resp.data


if __name__ == '__main__':
    unittest.main()
